package jehc.djshi.common.util;

import org.springframework.util.CollectionUtils;
import java.util.*;

/**
 * @Desc 拆分集合
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
public class CollectionUtil {
    /**
     * map拆分
     * @param chunkMap 被切段的 map
     * @param chunkNum 每段的大小 （传递数量 会自动拆分多少组（List<Map<k,v></>>））
     * @param <k>      map 的 key类 型
     * @param <v>      map 的value 类型
     * @return List
     */
    public static <k, v> List<Map<k, v>> mapChunk(Map<k, v> chunkMap, int chunkNum) {
        if (chunkMap == null || chunkNum <= 0) {
            List<Map<k, v>> list = new ArrayList<>();
            list.add(chunkMap);
            return list;
        }
        Set<k> keySet = chunkMap.keySet();
        Iterator<k> iterator = keySet.iterator();
        int i = 1;
        List<Map<k, v>> total = new ArrayList<>();
        Map<k, v> tem = new HashMap<>();
        while (iterator.hasNext()) {
            k next = iterator.next();
            tem.put(next, chunkMap.get(next));
            if (i == chunkNum) {
                total.add(tem);
                tem = new HashMap<>();
                i = 0;
            }
            i++;
        }
        if (!CollectionUtils.isEmpty(tem)) {
            total.add(tem);
        }
        return total;
    }


    /**
     * 将 list 切成段
     * @param chunkNum 每段的大小
     * @param list
     * @return map 每一 Kye 中有 chunkNum 条数据
     */
    public static LinkedHashMap groupList(List list, int chunkNum) {
        int listSize = list.size();
        int toIndex = chunkNum;
        LinkedHashMap map = new LinkedHashMap();
        int keyToken = 0;
        for (int i = 0; i < listSize; i += chunkNum) {
            if (i + chunkNum > listSize) {
                toIndex = listSize - i;
            }
            List newList = list.subList(i, i + toIndex);
            map.put("keyName" + (keyToken + 1), newList);
            keyToken++;
        }
        return map;
    }


    /**
     * @Description:按个数分组
     * @param dataList
     * @param groupNumber 代表每组的个数
     * @return 返回所有的组
     */
    public static <T> List<List<T>> groupCollection(Collection<T> dataList, int groupNumber) {
        List<List<T>> returnDatas = new ArrayList<List<T>>();
        List<T> unit = null;
        int counter = 0;
        for (T t : dataList) {
            if (counter % groupNumber == 0) {
                unit = new ArrayList<T>();
                returnDatas.add(unit);
            }
            unit.add(t);
            counter++;
        }
        return returnDatas;
    }
}
